import { useMemo } from 'react'
import useChartDataInfo from '../useChartDataInfo'

function useSeries(widgetId, type) {
  const {
    data = [],
    indexToFieldArray = [],
    keyToFieldObject,
    valueKey
  } = useChartDataInfo(widgetId)

  const series = useMemo(() => {
    const getIndex = (id) => indexToFieldArray.findIndex((v) => id === v)
    const getSeries = (index, name) => ({
      name,
      type,
      data: data.map((v) => v[index])
    })

    const valueIndex = getIndex(valueKey)
    const seriesArr = [getSeries(valueIndex)]

    const values = keyToFieldObject?.valueKey || []
    for (const { id, title } of values.values()) {
      if (id === valueKey) {
        seriesArr[0].name = title
        continue
      }
      const index = getIndex(id)
      seriesArr.push(getSeries(index, title))
    }

    return seriesArr
  }, [data, indexToFieldArray, keyToFieldObject, valueKey, type])

  return series
}

export default useSeries
